#include <QApplication>
#include <QTableWidget>
#include <QString>

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    // 初始化8行4列的tableWidget
    QTableWidget tableWidget(8, 4);
    // 获取tableWdiget的selectionModel
    QItemSelectionModel *selectionModel = tableWidget.selectionModel();

    // 创建一个选区，指定左上角和右下角的modelIndex
    // 选区大小不超过model大小
    QModelIndex topLeft = tableWidget.model()->index(0, 0, QModelIndex());
    QModelIndex rightBottom = tableWidget.model()->index(4, 2, QModelIndex());
    QItemSelection selection(topLeft, rightBottom);

    // 选中选区， QItemSelectionModel::Select表示选区内的所有元素都被选中
    selectionModel->select(selection, QItemSelectionModel::Select);

    // 获取选区中model的所有index
    QModelIndexList indexs = selectionModel->selectedIndexes();
    // 遍历indexs, 加入数据
    foreach (QModelIndex index, indexs) {
        QString text = QString("(%1, %2)").arg(index.row()).arg(index.column());
        tableWidget.model()->setData(index, text);
    }

    tableWidget.resize(600, 600);
    tableWidget.show();

    return app.exec();
}
